<?php
/**
 * Created by PhpStorm.
 * 客户经理服务层
 * User: xuewl
 * Date: 2017/12/22
 * Time: 23:58
 */

namespace app\user\service;
use app\common\library\Service;
use Overtrue\Pinyin\Pinyin;

class Customer extends Service
{
    use \app\common\library\traits\Model;
    protected $model;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('user/user');
    }

    /**
     * 创建客户经理
     * @param $user_id
     * @param string $code
     * @param string $realname
     * @param string $mobile 手机号码
     * @return bool
     */
    public function create($user_id, $code, $realname, $mobile = '') {
        $user = $this->model->find($user_id);
        if(!$user || $user['status'] == 0) {
            $this->error = "用户状态异常";
            return false;
        }

        if($user['role'] == 2) {
            $this->error = "该用户已经是客户经理";
            return false;
        }

        $is_exist = $this->model->where([
            'customer_code' => $code,
            'role' => 2,
        ])->value('id');

        if($is_exist > 0) {
            $this->error = "客户经理编号已被占用";
            return false;
        }


        $PinyinObj = new Pinyin();
        $pinyin = $PinyinObj->name($realname);

        $info = [
            'id' => $user_id,
            'role' => 2,
            'customer_code' => $code,
            'customer_realname' => $realname,
            'mobile' => $mobile,
            'customer_pinyin' => $pinyin[0][0],
        ];

        $result = $this->save($info, ['id' => $user_id], 'customer');
        if(!$result) {
            $this->error = $this->getError();
            return false;
        }
        \think\Hook::listen("UserCustomerCreateAfter", $result);
        return $result;
    }

    /**
     * 取消客户经理
     * @param integer $user_id
     * @param integer $role
     * @return boolean
     */
    public function cancel($user_id, $role = 0) {
        $user = $this->model->where([
            'id' => $user_id,
            'status' => 1,
        ])->find();

        if(!$user) {
            $this->error = "用户不存在或已被禁用";
            return false;
        }

        if($user['role'] !== 2) {
            $this->error = "该用户不是客户经理";
            return false;
        }

        $info = [
            'id' => $user_id,
            'role' => $role,
            'customer_code' => '',
            'customer_realname' => '',
            'customer_pinyin' => '',
        ];
        $result = $this->save($info, ['id' => $user_id], 'customer');
        if(!$result) {
            $this->error = $this->getError();
            return false;
        }
        \think\Hook::listen("UserCustomerCancelAfter", $result);
        return $result;
    }
}